<?php

namespace App\Http\Controllers\Api\Record;

use App\Http\Controllers\ApiController;
use App\Http\Requests\AuxiliaryStoreRequest;
use App\Http\Requests\AuxiliaryUpdateRequest;
use App\Models\MedicalAuxiliary;
use App\Models\MedicalRecord;
use App\Project\Filters\AuxiliaryFilter;
use App\Project\Transform;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;

class AuxiliaryController extends ApiController
{
    /**
     * @param \App\Http\Requests\AuxiliaryStoreRequest $request
     * @return mixed
     * @throws \Throwable
     */
    public function store(AuxiliaryStoreRequest $request)
    {
        $input = $this->extendFiled((new AuxiliaryFilter($request))->input());

        return \DB::transaction(function () use ($input) {
            $result = MedicalAuxiliary::updateOrCreate(['record_id' => $input['record_id']], $this->convertArrayToJson($input));

            //  将辅助检查的打印选项 数字字符串(例：1,2,3)保存至病历表的 print_auxiliary字段
            if ($printId = $this->getPrintId($input)->implode(',')) {
                MedicalRecord::where(['id' => $input['record_id']])->update(['print_auxiliary' => $printId]);
            }

            return $this->response(['id' => $result['id']]);
        });
    }

    /**
     * 根据输入数据返回需要打印的ID列表
     * @param $input
     * @return \Illuminate\Support\Collection
     */
    protected function getPrintId($input)
    {
        $print = collect($input)->reject(function ($value) {

            if (isset($value['print']))
                return ($value['print'] == 'on') ? false : true;

            return true;
        })->keys()->toArray();

        $printMap = app('field')->get('auxiliary.print');

        return collect($printMap)->pluck('field')->combine(array_keys($printMap))->only($print);
    }

    public function edit(Request $request)
    {
        $data = null;
        $id   = $request->get('id');

        $select = ['id', 'record_id', 'saccharify', 'acr', 'biochemical_examination', 'ogtt'];

        if ($id > 0) {

            $data = MedicalAuxiliary::select($select)->findOrFail($id);
        } elseif ($record_id = $request->get('record_id')) {
            $data = MedicalAuxiliary::select($select)->where(['record_id' => $record_id])->first();
        } else {
            abort(400, '缺失辅助检查ID，或者病历ID');
        }

        if (empty($data)) {
            throw (new ModelNotFoundException())->setModel(MedicalAuxiliary::class);
        }

        return $this->item($data, function (MedicalAuxiliary $auxiliary) {

            $data = $auxiliary->toArray();
            if (is_array($data['biochemical_examination'])) {
                $data['biochemical_examination'] = array_intersect_key(
                    $data['biochemical_examination'],
                    array_flip(['alt', 'ast', 'cr(e)', 'ldl-c'])
                );
            }

            return $data;
        });
    }

    public function update(AuxiliaryUpdateRequest $request)
    {
        $where = [];

        if ($id = $request->input('id')) {
            $where['id'] = $id;
        } else {
            $where['record_id'] = $request->input('record_id');
        }

        $input = (new AuxiliaryFilter($request))->except(['id', 'record_id']);

        $input = (new Transform())->setArray($this->extendFiled($input))->convertArrayToJson(
            [
                'ogtt', 'saccharify', 'acr', 'biochemical_examination', 'liver_function', 'kidney',
                'tg_chohdlldl'
            ]
        )->get();

        $result = MedicalAuxiliary::where($where)->update($input);

        return $this->responseForUpdate($result);
    }

    public function extendFiled($input)
    {
        $extend = [];

        if (isset($input['biochemical_examination']['alt'])) {
            $extend['liver_function']['alt'] = $input['biochemical_examination']['alt'];
        }

        if (isset($input['biochemical_examination']['ast'])) {
            $extend['liver_function']['ast'] = $input['biochemical_examination']['ast'];
        }

        if (isset($input['biochemical_examination']['cr(e)'])) {
            $extend['kidney']['cr(e)'] = $input['biochemical_examination']['cr(e)'];
        }

        if (isset($input['biochemical_examination']['ldl-c'])) {
            $extend['tg_chohdlldl']['ldl-c'] = $input['biochemical_examination']['ldl-c'];
        }

        foreach ($input as &$value) {
            if (is_array($value)) {
                $filled = false;
                foreach ($value as $item) {
                    if (empty($item)) {
                        continue;
                    }
                    $filled = true;
                    continue;
                }

                if ($filled) {
                    $value = array_merge($value, ['print' => 'on', 'time' => Carbon::now()->toDateString()]);
                }
            }
        }

        return array_merge($extend, $input);
    }

    public function convertArrayToJson($input)
    {
        return (new Transform())->setArray($input)->convertArrayToJson(
            [
                'blood', 'insulin', 'peptide_c', 'ogtt', 'saccharify', 'diabetes_antibody', 'acr', 'uaer',
                'urine_routine', 'biochemical_examination', 'liver_function', 'kidney', 'electrolyte',
                'tg_chohdlldl',
                'bt_paba', 'thyroid_function_one', 'thyroid_function_two', 'thyroid_function_three', 'plasma_acth',
                'blood_cortisol',
                'endocrine_examination', 'growth_hormone', 'insulin_growth_factor', 'blood_routine',
                'blood_gas_analysis',
                'blood_coagulation_two', 'dexamethasone_suppression', 'hydroxyvitamin', 'uca_up',
                'collagen_degradation',
                'iconography'
            ]
        )->get();
    }
}
